package com.jaks.xpense;

import java.util.Calendar;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.jaks.xpense.data.Expenses;
import com.jaks.xpense.utils.Globals;
import com.jaks.xpense.utils.WidgetUtils;

public class UpdateService extends Service {

	@Override
	public void onStart(Intent intent, int startId) {
		RemoteViews updateViews = buildUpdate(this);
		WidgetUtils.updateWidget(this, updateViews);
	}

	public RemoteViews buildUpdate(Context context) {

		Expenses expenses = null;
		RemoteViews remoteViews = null;

		try {
			expenses = new Expenses(context);
			remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgethome);

			String today = Globals.toDateText(Calendar.getInstance());
			double todayTotal = expenses.getTotalAmount(today, today);
			double balance = expenses.getBalance();

			WidgetUtils.updateView(context, remoteViews, String.valueOf(todayTotal),
			    String.valueOf(balance));
		} catch (Exception ex) {
		} finally {
			if (expenses != null)
				expenses.close();
		}
		return remoteViews;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
